﻿using Currency.IServices.User;
using System.Threading.Tasks;
using User.IServices.Dto;
using Currency.Infra.IRepository;
using System.Net;
using Currency.Services.Shared.Extension;
using Currency.Infra.Helper;
using User.Entity.Entities;
using Currency.IServices.Shared.Models;

namespace User.Services
{
    /// <summary>
	/// UserInfoServices
	/// </summary>
    public class UserInfoServices : AbstractService, IUserInfoServices
    {
        private IBaseRepository<UserInfo> _userDal;

        public UserInfoServices(IBaseRepository<UserInfo> userDal)
        {
            this._userDal = userDal;
        }

        /// <summary>
		/// 用户注册
		/// </summary>
		/// <param name="userInfo">用户</param>
		/// <returns>主键</returns>
        public async Task<ResultMessage<long>> Create(UserRegisterDto userInfoView)
        {
            var isExc = await _userDal.AnyAsync(x => x.Account == userInfoView.Account);
            if (isExc)
                return ErrorDetails(HttpStatusCode.BadRequest, "账号已经存在");

            var user = Mapper.Map<UserInfo>(userInfoView);
            user.Id = IdGenerater.GetNextId();//雪花ID
            user.Account = user.Account.ToLower();
            user.Salt = SecurityHelper.GenerateRandomCode(5);//密码盐
            user.Password = HashHelper.GetHashedString(HashType.MD5, user.Password, user.Salt);

            //布隆过滤器
            //var cacheKey = _cacheService.ConcatCacheKey(CachingConsts.UserValidateInfoKeyPrefix, user.Id);
            //var bloomFilterCacheKey = _bloomFilterFactory.GetBloomFilter(nameof(BloomFilterCacheKey));
            //await bloomFilterCacheKey.AddAsync(cacheKey);

            //var bloomFilterAccount = _bloomFilterFactory.GetBloomFilter(nameof(BloomFilterAccount));
            //await bloomFilterAccount.AddAsync(user.Account);

            await _userDal.InsertAsync(user);

            return user.Id;
        }
    }
}
